package com.xuebusi.toutiao.admin.api.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuebusi.toutiao.admin.api.common.config.GlobalConfig;
import com.xuebusi.toutiao.admin.api.common.exception.CustomException;
import com.xuebusi.toutiao.admin.api.common.result.ApiResult;
import com.xuebusi.toutiao.admin.api.common.result.PageInfo;
import com.xuebusi.toutiao.admin.api.user.dao.FollowerDao;
import com.xuebusi.toutiao.admin.api.user.entity.FollowerEntity;
import com.xuebusi.toutiao.admin.api.user.entity.UserEntity;
import com.xuebusi.toutiao.admin.api.user.service.FollowerService;
import com.xuebusi.toutiao.admin.api.user.service.UserService;
import com.xuebusi.toutiao.admin.api.user.vo.FollowerVO;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("followerService")
public class FollowerServiceImpl extends ServiceImpl<FollowerDao, FollowerEntity> implements FollowerService {
    @Resource
    private GlobalConfig globalConfig;

    @Resource
    private UserService userService;

    /**
     * 查询粉丝列表
     *
     * @param userId      用户id
     * @param currentPage 页码
     * @param pageSize    每页个数
     * @return
     * @throws CustomException
     */
    @Override
    public ResponseEntity<ApiResult<PageInfo<FollowerVO>>> followers(
            Integer userId, int currentPage, int pageSize) throws CustomException {
        // 分页查询
        Page<FollowerEntity> page = new Page<>(currentPage, pageSize);
        List<FollowerEntity> followers = this.page(page,
                new QueryWrapper<FollowerEntity>().eq("user_id", userId)).getRecords();
        List<FollowerVO> results = new ArrayList<>();
        for (FollowerEntity follower : followers) {
            UserEntity userEntity = userService.getById(follower.getFollowerId());
            FollowerVO followerVO = new FollowerVO();
            followerVO.setId(userEntity.getId());
            followerVO.setName(userEntity.getName());
            followerVO.setPhoto(globalConfig.getWebSite() + userEntity.getPhoto());
            results.add(followerVO);
        }
        PageInfo pageInfo = new PageInfo(page.getCurrent(), page.getSize(), page.getTotal(), results);
        pageInfo.setResults(results);

        ApiResult apiResult = new ApiResult();
        apiResult.setData(pageInfo);
        return ResponseEntity.ok(apiResult.ok(pageInfo));
    }
}
